package top.jnaw.jee.platform.model;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import java.util.List;
import top.jnaw.jee.platform.Consts;
import top.jnaw.jee.platform.Consts.Result;
import top.jnaw.jee.platform.model.base.BaseMediation;
import top.jnaw.jee.utils.Dates;
import top.jnaw.jee.utils.Log;
import top.jnaw.jee.utils.ModelResult;
import top.jnaw.jee.utils.Models;
import top.jnaw.jee.utils.Strings;
import top.jnaw.jee.utils.wechat.Wechats;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class Mediation extends BaseMediation<Mediation> {

  public static final Mediation dao = new Mediation().dao();

  public static ModelResult add(String openid, String req, String process,
      String require, JSONArray person, JSONArray accessory) {
    ModelResult result = new ModelResult(Result.kModelSaveError);
    WechatUsers wechatUsers = WechatUsers.getByOpenid(openid);
    if (null != wechatUsers) {
      result = Approval.add(wechatUsers.getId(), 3, "调解申请", null, null);
      if (result.fine()) {
        Approval approval = (Approval) result.getObject();
        if (null != approval) {
          Mediation mediation = new Mediation();
          mediation.setCreateTime(Dates.now());
          mediation.setOpenid(openid);
          mediation.setAid(approval.getId());
          mediation.setProcess(process);
          mediation.setReq(req);
          mediation.setRequire(require);
          boolean r = mediation.save();
          if (r) {
            if (null != person && person.size() > 0) {
              r = MediationPerson.add(mediation.getId(), person);
            }
            if (null != accessory && accessory.size() > 0) {
              r = FileModel.add(6, mediation.getId(), accessory, "accessory");
            }
            result.setObject(mediation);
            result.setResult(r ? Result.kSuccess : Result.kNext);
          }
        }
      }
    }
    return result;
  }

  public static JSONObject list(int page, int size, JSONArray filter, int uid) {
    String sec = Db.getSql("mediation-list-sec");
    String exp = Db.getSql("mediation-list-exp");
    Object openid = Strings.get(filter, "openid", false);
    Object status = Strings.get(filter, "status", false);
    Object is_start = Strings.get(filter, "is_start", false);
    if (null != openid) {
      exp += " AND m.openid = '" + openid.toString() + "'";
    }
    if (uid > 0) {
      exp += " AND ar.approver= " + uid;
    }
    if (null != status) {
      if (Consts.APPROVAL_CHECKED.equals(status.toString())) {
        exp += " AND ar.status !='cancel' AND ar.status !='checking'";
      } else {
        exp += " AND ar.status = '" + status.toString() + "'";
      }
    }
    if (null != is_start) {
      exp += " AND m.is_start = " + is_start;
    }
    exp += " order by m.create_time desc ";
    Page<Record> pages = Db.paginate(page, size, sec, exp);
    return Models.compressPage(pages);
  }

  public static ModelResult query(int id) {
    ModelResult result = new ModelResult(Result.kNull);
    JSONObject object = null;
    int did = -1;
    String sql = Db.getSql("mediation-query");
    List<Mediation> list = dao.find(sql, id);
    if (null != list && list.size() > 0) {
      object = Models.compressList(list);
      if (null != object.get("did")) {
        did = object.getInteger("did");
      }
      String name = Consts.APPROVAL_MEDIATION_SECOND_DNAME;
      if (did > 0) {
        Department department = Department.dao.findById(did);
        if (null != department) {
          name = department.getName();
        }
      }
      JSONArray reply = object.getJSONArray("reply");
      if (null != reply && reply.size() > 0) {
        reply.getJSONObject(0)
            .put("dname", Consts.APPROVAL_MEDIATION_FIRST_DNAME);
        if (reply.size() - 1 > 0) {
          reply.getJSONObject(reply.size() - 1).put("dname", name);
        }
        for (int i = 0; i < reply.size(); i++) {
          reply.getJSONObject(i).put("accessory", FileModel
              .list(1, reply.getJSONObject(i).getInteger("id"), "accessory",
                  false));
        }
      }
      object = MediationPerson.merge(id, object);
      object.put("accessory", FileModel.list(6, id, "accessory", false));
    }
    if (null != object) {
      result.setObject(object);
      result.setResult(Result.kSuccess);
    }
    return result;
  }

  public static ModelResult queryArb(int id) {
    ModelResult result = new ModelResult(Result.kNull);
    JSONObject object = null;
    String sql = Db.getSql("arbitration-query");
    List<Mediation> list = dao.find(sql, id);
    if (null != list && list.size() > 0) {
      object = Models.compressList(list);
      object = MediationPerson.merge(id, object);
      object.put("accessory", FileModel.list(6, id, "accessory", false));
      object.put("receipt", FileModel.list(7, id, "receipt", false));
      object.put("notice", FileModel.list(7, id, "notice", false));
      object.put("ruling", FileModel.list(7, id, "ruling", false));
    }
    if (null != object) {
      result.setObject(object);
      result.setResult(Result.kSuccess);
    }
    return result;
  }

  public static ModelResult add(int mid) {
    ModelResult result = new ModelResult(Result.kModelSaveError);
    Mediation mediation = dao.findById(mid);
    if (null != mediation) {
      mediation.setIsStart(true);
      boolean r = mediation.update();
      if (r) {
        result.setObject(mediation);
        result.setResult(Result.kSuccess);
      }
    }
    return result;
  }

  public static ModelResult updateStatus(int aid, String status) {
    ModelResult result = new ModelResult(Result.kModelUpdateError);
    Mediation mediation = dao
        .findFirst("select * from mediation where aid=?", aid);
    if (null != mediation) {
      mediation.setStatus(status);
      boolean r = mediation.update();
      if (r) {
        result.setObject(mediation);
        result.setResult(Result.kSuccess);
      }
    }
    return result;
  }

  public static ModelResult updateStage(int id, String type,
      JSONArray accessory) {
    ModelResult result = new ModelResult(Result.kModelUpdateError);
    boolean r = true;
    Mediation mediation = dao.findById(id);
    if (null != mediation) {
      if (null != accessory && accessory.size() > 0) {
        r = FileModel.add(7, id, accessory, type);
      }
      if (r) {
        switch (type) {
          case "receipt":
            mediation.setStage("receipted");
            break;
          case "notice":
            mediation.setStage("noticed");
            break;
          case "ruling":
            mediation.setStage("rulinged");
            break;
          case "ruling_paged":
            mediation.setStage("ruling_paged");
            break;
          default:
            Log.e("error type");
        }
        r = mediation.update();
        if (r) {
          result.setResult(Result.kSuccess);
          result.setObject(mediation);
        }
      }
    }
    return result;
  }

  public static ModelResult send(int id, String type, String content,
      String date, String address) {

    ModelResult result = new ModelResult(Result.kBadType);
    JSONArray array = MediationPerson.getOpenids(id);
    if (null != array && array.size() > 0) {
      switch (type) {
        case "notice":
          Wechats
              .holdCourt("您好，您近期有开庭安排", date, address, content, id,
                  "请务必准时出庭", "mediation", array);
          result.setResult(Result.kSuccess);
          break;
        case "ruling":
          Wechats
              .stage("您好，您申请的仲裁已裁定", "土地承包纠纷仲裁", "裁定书已下达", content,
                  "历城区仲裁委员会", id, "请您在收到此通知后，尽快点击查看详情", "arbitration", array);
          result.setResult(Result.kSuccess);
          break;
        case "ruling_page":
          Wechats
              .stage("您好，您申请的仲裁，纸质版裁定书已邮寄", "土地承包纠纷仲裁", "裁定书已邮寄", content,
                  "历城区仲裁委员会", id, "请您在收到此通知后，点击进入详情页面，确认收到", "arbitration",
                  array);
          result.setResult(Result.kSuccess);
          break;
        default:
          Log.e("bad type");
      }
    }
    return result;

  }
}
